package physical_spaces.DAO;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import login.beans.ConectionBean;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.pool.OracleDataSource;

/**
 *
 * @author juan
 */
public class CreateControlFileDAO {

    public void CreateControlFile(String sql, Connection connection)throws SQLException  {
        
        try (Statement statement = connection.createStatement()) {
            statement.executeQuery(sql);
            statement.close();
        }
        
    }
    
    public void stopDatabase() throws SQLException {

        try {

            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().
                    getExternalContext().getSession(false);
            ConectionBean bean = (ConectionBean) session.getAttribute("conectionBean");            
            Properties prop = new Properties();
            prop.setProperty("user", "SYS as sysdba");
            prop.setProperty("password", bean.getPassword());
            OracleDataSource ods = new OracleDataSource();
            ods.setConnectionProperties(prop);
            String url = "jdbc:oracle:thin:@";
            url = url + bean.getHost() + ":";
            url = url + bean.getDatabase();
            ods.setURL(url);
            System.out.println(url);
            try{
                bean.currentConnection.close();
                session.invalidate();
                
            }catch(SQLException e){
                System.out.println(e);
            }
            OracleConnection conn = (OracleConnection) ods.getConnection();
            System.out.println("Connected");
            conn.shutdown(OracleConnection.DatabaseShutdownMode.IMMEDIATE);
            System.out.println("Instance stopped");
            Statement stmt = conn.createStatement();
            stmt.execute("ALTER DATABASE CLOSE NORMAL");
            stmt.execute("ALTER DATABASE DISMOUNT");
            stmt.close();
            System.out.println("Database closed and dismounted");
            conn.shutdown(OracleConnection.DatabaseShutdownMode.FINAL);
            conn.close();
            ods.close();
            System.out.println("Connection Closed");

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
          
    }
}